const express = require('express')
const cors = require('cors')
const { OpenAI } = require('openai')
require('dotenv').config()
const PDFDocument = require('pdfkit')
const Docxtemplater = require('docxtemplater')
const PizZip = require('pizzip')
const fs = require('fs')
const path = require('path')
const { Readable } = require('stream')

const app = express()
const PORT = process.env.PORT || 5000

// Initialize AI client based on provider
let aiClient
let aiBaseURL

if (process.env.AI_PROVIDER === 'bailian') {
  // 阿里云百炼配置
  aiClient = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: process.env.BAILIAN_API_URL || 'https://dashscope.aliyuncs.com/compatible-mode/v1'
  })
  aiBaseURL = process.env.BAILIAN_API_URL || 'https://dashscope.aliyuncs.com/compatible-mode/v1'
} else {
  // 默认OpenRouter配置
  aiClient = new OpenAI({
    apiKey: process.env.OPENROUTER_API_KEY,
    baseURL: 'https://openrouter.ai/api/v1'
  })
  aiBaseURL = 'https://openrouter.ai/api/v1'
}

// Middleware
app.use(cors())
app.use(express.json())

// AI content generation (supports bailian and openrouter)
const generateAIContent = async (topic, type) => {
  try {
    const prompt = `请为主题"${topic}"写一篇高质量的微信公众号文章。

要求：
1. 文章结构清晰，包含引言、主要内容、结语
2. 内容有深度，有实用价值
3. 语言生动有趣，适合公众号阅读
4. 使用Markdown格式
5. 字数控制在800-1500字
6. 包含小标题和重点标记

请直接输出文章内容，不需要额外说明。`

    const options = {
      // 使用正确的模型名称
      model: process.env.AI_MODEL || 'chatglm3-6b',
      messages: [
        {
          role: 'system',
          content: '你是一个专业的公众号文章写手，擅长创作有深度、有趣味的文章内容。'
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      temperature: 0.8,
      max_tokens: 2000
    }

    // 添加特定提供商的配置
    if (process.env.AI_PROVIDER === 'openrouter') {
      options.extra_headers = {
        'HTTP-Referer': process.env.SITE_URL || '',
        'X-Title': process.env.SITE_NAME || ''
      }
    }

    const completion = await aiClient.chat.completions.create(options)

    const content = completion.choices[0].message.content
    const title = content.split('\n')[0].replace(/^#\s*/, '') || `${topic} - 深度解析`

    return {
      title,
      content
    }
  } catch (error) {
    console.error('DeepSeek API Error:', error)
    throw error
  }
}

// Fallback mock content generation
const generateMockContent = (topic, type) => {
  const templates = {
    article: {
      title: `${topic} - 深度解析与未来展望`,
      content: `# ${topic} - 深度解析与未来展望

## 引言

在当今快速发展的时代，${topic}已经成为了一个备受关注的话题。本文将深入探讨相关内容，为读者提供全面的分析和见解。

## 核心观点

### 1. 基础概念
${topic}涉及多个层面的内容，需要我们从不同角度来理解和分析。

### 2. 发展趋势
- 技术创新推动发展
- 市场需求不断增长
- 政策支持力度加大

### 3. 实际应用
在实际应用中，${topic}展现出了巨大的潜力：

1. **提高效率**: 通过优化流程，显著提升工作效率
2. **降低成本**: 减少不必要的资源浪费
3. **改善体验**: 为用户提供更好的服务体验

## 案例分析

通过分析相关案例，我们可以看到${topic}在各个领域的成功应用。这些案例为我们提供了宝贵的经验和启示。

### 成功要素
- 明确的目标定位
- 合理的资源配置
- 有效的执行策略

## 挑战与机遇

虽然${topic}带来了诸多机遇，但同时也面临着一些挑战：

**机遇方面：**
- 市场空间巨大
- 技术不断进步
- 政策环境友好

**挑战方面：**
- 竞争日趋激烈
- 技术门槛较高
- 人才需求旺盛

## 未来展望

展望未来，${topic}将在以下方面取得重要进展：

1. **技术突破**: 核心技术将实现重大突破
2. **应用拓展**: 应用场景将更加丰富多样
3. **生态完善**: 产业生态将日趋完善

## 结语

总的来说，${topic}作为一个重要的发展方向，值得我们持续关注和深入研究。只有把握好发展趋势，积极应对挑战，才能在这个领域取得成功。

---

*本文由 WechatAiWriter AI 智能生成，内容仅供参考。如需了解更多信息，请关注我们的后续文章。*`
    }
  }

  return templates[type] || {
    title: topic,
    content: `# ${topic}\n\n这是一篇关于${topic}的文章。\n\n## 主要内容\n\n请在此处添加具体内容...`
  }
}

// Routes

// Health check
app.get('/api/health', (req, res) => {
  res.json({ status: 'OK', message: 'WechatAiWriter API is running' })
})

// Generate content
app.post('/api/generate', async (req, res) => {
  try {
    const { topic, type = 'article' } = req.body

    if (!topic) {
      return res.status(400).json({ 
        error: '请提供主题内容' 
      })
    }

    let generatedContent
    let source = 'mock'

    // Try configured AI provider first, fallback to mock if fails
    try {
      console.log(`🤖 Using ${process.env.AI_PROVIDER || 'default'} (${process.env.AI_MODEL}) to generate content for: ${topic}`)
      generatedContent = await generateAIContent(topic, type)
      source = process.env.AI_PROVIDER || 'default'
    } catch (aiError) {
      console.warn(`${process.env.AI_PROVIDER || 'AI'} API failed, using fallback:`, aiError.message)
      // 更详细的错误分类
      if (aiError.status === 402) {
        console.warn('API余额不足或访问受限')
      } else if (aiError.status === 401) {
        console.warn('API Key无效，请检查配置')
      } else if (aiError.status === 429) {
        console.warn('API请求频率过高，请稍后再试')
      } else if (aiError.status === 400) {
        console.warn('API请求参数错误，可能是模型名称不正确')
      }
      generatedContent = generateMockContent(topic, type)
    }

    res.json({
      success: true,
      title: generatedContent.title,
      content: generatedContent.content,
      timestamp: new Date().toISOString(),
      source: source,
      // 添加更多调试信息
      debug: {
        model: process.env.AI_MODEL,
        provider: process.env.AI_PROVIDER
      }
    })

  } catch (error) {
    console.error('Content generation error:', error)
    res.status(500).json({
      success: false,
      error: '内容生成失败，请稍后重试',
      // 提供更详细的错误信息以便调试
      details: error.message || '未知错误',
      // 即使出错也返回模拟内容，确保前端能正常展示
      fallbackContent: generateMockContent(topic || '系统错误', type)
    })
  }
})

// 辅助函数：将Markdown解析为用于PDF的结构化内容
function parseMarkdownForPDF(content) {
  const sections = []
  let currentSection = { type: 'paragraph', text: '' }
  
  const lines = content.split('\n')
  lines.forEach(line => {
    line = line.trim()
    
    if (line.startsWith('# ')) {
      if (currentSection.text) sections.push(currentSection)
      currentSection = { type: 'h1', text: line.substring(2).trim() }
    } else if (line.startsWith('## ')) {
      if (currentSection.text) sections.push(currentSection)
      currentSection = { type: 'h2', text: line.substring(3).trim() }
    } else if (line.startsWith('### ')) {
      if (currentSection.text) sections.push(currentSection)
      currentSection = { type: 'h3', text: line.substring(4).trim() }
    } else if (line.startsWith('- ') || line.startsWith('* ')) {
      if (currentSection.type !== 'list') {
        if (currentSection.text) sections.push(currentSection)
        currentSection = { type: 'list', items: [line.substring(2).trim()] }
      } else {
        currentSection.items.push(line.substring(2).trim())
      }
    } else if (line === '') {
      if (currentSection.text || (currentSection.type === 'list' && currentSection.items.length > 0)) {
        sections.push(currentSection)
        currentSection = { type: 'paragraph', text: '' }
      }
    } else {
      // 处理加粗和斜体
      let processedText = line
        .replace(/\*\*(.*?)\*\*/g, (match, p1) => `**${p1}**`) // 保留加粗标记
        .replace(/\*(.*?)\*/g, (match, p1) => `*${p1}*`) // 保留斜体标记
      
      if (currentSection.type === 'paragraph') {
        currentSection.text += (currentSection.text ? '\n' : '') + processedText
      } else {
        if (currentSection.text || (currentSection.type === 'list' && currentSection.items.length > 0)) {
          sections.push(currentSection)
        }
        currentSection = { type: 'paragraph', text: processedText }
      }
    }
  })
  
  if (currentSection.text || (currentSection.type === 'list' && currentSection.items.length > 0)) {
    sections.push(currentSection)
  }
  
  return sections
}

// Export content
app.post('/api/export', (req, res) => {
  try {
    const { content, format = 'markdown', filename, title = '文章标题' } = req.body

    if (!content) {
      return res.status(400).json({ 
        error: '请提供要导出的内容' 
      })
    }

    // 处理PDF格式
    if (format === 'pdf') {
      const doc = new PDFDocument()
      const chunks = []
      
      doc.on('data', chunk => chunks.push(chunk))
      doc.on('end', () => {
        const pdfBuffer = Buffer.concat(chunks)
        res.json({
          success: true,
          content: pdfBuffer.toString('base64'),
          contentType: 'application/pdf',
          filename: filename || `${title || 'article'}.pdf`,
          isBinary: true
        })
      })
      
      // 添加标题
      if (title) {
        doc.fontSize(24).font('Helvetica-Bold').text(title, { align: 'center' })
        doc.moveDown(2)
      }
      
      // 解析Markdown并添加到PDF
      const sections = parseMarkdownForPDF(content)
      sections.forEach(section => {
        switch (section.type) {
          case 'h1':
            doc.fontSize(20).font('Helvetica-Bold').text(section.text)
            doc.moveDown()
            break
          case 'h2':
            doc.fontSize(18).font('Helvetica-Bold').text(section.text)
            doc.moveDown()
            break
          case 'h3':
            doc.fontSize(16).font('Helvetica-Bold').text(section.text)
            doc.moveDown()
            break
          case 'paragraph':
            // 处理加粗和斜体
            let text = section.text
            let currentFont = 'Helvetica'
            let currentSize = 12
            let inBold = false
            let inItalic = false
            
            const parts = text.split(/(\*\*|\*)/)
            parts.forEach((part, index) => {
              if (index === 0 && part) {
                doc.font(currentFont).fontSize(currentSize).text(part, { continued: parts.length > 1 })
              } else if (part === '**') {
                inBold = !inBold
                currentFont = inBold ? 'Helvetica-Bold' : 'Helvetica'
                // 如果是最后一个元素，不添加continued
                if (index < parts.length - 1) {
                  doc.font(currentFont).fontSize(currentSize).text('', { continued: true })
                }
              } else if (part === '*') {
                inItalic = !inItalic
                currentFont = inItalic ? 'Helvetica-Oblique' : 'Helvetica'
                // 如果是最后一个元素，不添加continued
                if (index < parts.length - 1) {
                  doc.font(currentFont).fontSize(currentSize).text('', { continued: true })
                }
              } else if (part) {
                // 如果是最后一个元素，不添加continued
                const isLast = index === parts.length - 1
                doc.font(currentFont).fontSize(currentSize).text(part, { continued: !isLast })
              }
            })
            doc.moveDown()
            break
          case 'list':
            section.items.forEach(item => {
              doc.fontSize(12).font('Helvetica').text(`• ${item}`)
            })
            doc.moveDown()
            break
        }
      })
      
      doc.end()
      return
    }
    
    // 处理DOCX格式
    if (format === 'docx') {
      try {
        // 创建一个简单的DOCX内容
        const docxContent = {
          title: title || '文章标题',
          content: content
        }
        
        // 创建一个基本的DOCX结构
        const zip = new PizZip()
        
        // 添加document.xml
        const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
          `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
          `<w:body>` +
          `<w:p><w:r><w:t xml:space="preserve">${docxContent.title}</w:t></w:r></w:p>` +
          `<w:p><w:r><w:t xml:space="preserve">${docxContent.content}</w:t></w:r></w:p>` +
          `</w:body>` +
          `</w:document>`
        
        zip.file('word/document.xml', documentXml)
        
        // 添加必要的XML关系
        zip.file('[Content_Types].xml', `<?xml version="1.0" encoding="UTF-8"?>` +
          `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
          `<Default Extension="xml" ContentType="application/xml"/>` +
          `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
          `</Types>`)
        
        zip.file('_rels/.rels', `<?xml version="1.0" encoding="UTF-8"?>` +
          `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
          `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>` +
          `</Relationships>`)
        
        zip.file('word/_rels/document.xml.rels', `<?xml version="1.0" encoding="UTF-8"?>` +
          `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
          `</Relationships>`)
        
        // 生成DOCX文件
        const docxBuffer = zip.generate({ type: 'nodebuffer' })
        
        res.json({
          success: true,
          content: docxBuffer.toString('base64'),
          contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          filename: filename || `${title || 'article'}.docx`,
          isBinary: true
        })
      } catch (docxError) {
        console.error('DOCX generation error:', docxError)
        res.status(500).json({ 
          error: 'DOCX生成失败，请稍后重试',
          details: docxError.message 
        })
      }
      return
    }

    // 处理其他文本格式
    let processedContent = content
    let contentType = 'text/plain'

    switch (format) {
      case 'html':
        processedContent = content
          .replace(/^# (.*$)/gm, '<h1>$1</h1>')
          .replace(/^## (.*$)/gm, '<h2>$1</h2>')
          .replace(/^### (.*$)/gm, '<h3>$1</h3>')
          .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
          .replace(/\*(.*?)\*/g, '<em>$1</em>')
          .replace(/^\- (.*$)/gm, '<li>$1</li>')
          .replace(/\n\n/g, '</p><p>')
          .replace(/^(?!<[h|li])(.+)(?![>])$/gm, '<p>$1</p>')
        contentType = 'text/html'
        break
      case 'wechat':
        processedContent = content
          .replace(/^# (.*$)/gm, '<h1 style="font-size: 24px; font-weight: bold; margin: 20px 0;">$1</h1>')
          .replace(/^## (.*$)/gm, '<h2 style="font-size: 20px; font-weight: bold; margin: 16px 0;">$1</h2>')
          .replace(/^### (.*$)/gm, '<h3 style="font-size: 16px; font-weight: bold; margin: 12px 0;">$1</h3>')
          .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
          .replace(/\*(.*?)\*/g, '<em>$1</em>')
          .replace(/^\- (.*$)/gm, '• $1')
        contentType = 'text/html'
        break
      default:
        // markdown
        contentType = 'text/markdown'
    }

    res.json({
      success: true,
      content: processedContent,
      contentType,
      filename: filename || `article.${format === 'html' ? 'html' : format === 'wechat' ? 'html' : 'md'}`
    })

  } catch (error) {
    console.error('Export error:', error)
    res.status(500).json({ 
      error: '导出失败，请稍后重试' 
    })
  }
})

// Start server
app.listen(PORT, () => {
  console.log(`🚀 WechatAiWriter API Server running on port ${PORT}`)
  console.log(`📝 Health check: http://localhost:${PORT}/api/health`)
})